

package com.hulk.dryad.common.component;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hulk.dryad.common.constant.CommonConstants;
import com.hulk.dryad.common.constant.enums.BEC;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.time.Instant;

/**
 * 响应信息主体
 *
 * @param <T>
 * @author hulk
 */
@Slf4j
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ApiModel(value = "响应信息主体")
public class R<T> implements Serializable {

	private static final long serialVersionUID = 1L;

	@Getter
	@Setter
	@ApiModelProperty(value = "返回标记：成功标记=0，失败标记=1")
	private int code;

	@Getter
	@Setter
	@ApiModelProperty(value = "返回信息")
	private String msg;

	@Getter
	@Setter
	@ApiModelProperty(value = "返回对象")
	private T data;

	@Getter
	@Setter
	@ApiModelProperty(value = "盐")
	private String salt;

	@Getter
	@Setter
	@ApiModelProperty(value = "签名信息")
	private String sign;

	public static <T> R<T> ok() {
		return restResult(null, CommonConstants.SUCCESS, null);
	}

	public static <T> R<T> ok(T data) {
		return restResult(data, CommonConstants.SUCCESS, null);
	}

	public static <T> R<T> ok(String msg,T data) {
		return restResult(data, CommonConstants.SUCCESS, msg);
	}

	public static <T> R<T> failed() {
		return restResult(null, CommonConstants.FAIL, null);
	}

	public static <T> R<T> failed(String msg) {
		return restResult(null, CommonConstants.FAIL, msg);
	}

	public static <T> R<T> failed(T data) {
		return restResult(data, CommonConstants.FAIL, null);
	}

	public static <T> R<T> failed( String msg, T data) {
		return restResult(data, CommonConstants.FAIL, msg);
	}

	public static <T> R<T> failed(int code, String msg) {
		return restResult(null, code, msg);
	}

	public static <T> R<T> failed( int code, String msg,T data) {
		return restResult(data, code, msg);
	}

	public static <T> R<T> failed(BEC bec) {
		return restResult(null, bec.getErrCode(), bec.getErrDesc());
	}
	public static <T> R<T> failed(BEC bec,T data) {
		return restResult(data, bec.getErrCode(), bec.getErrDesc());
	}
	private static <T> R<T> restResult(T data, int code, String msg) {
		R<T> api = new R<>();
		api.covert(api, data,  code,  msg);
		return api;
	}

	private  <T> R<T> covert(R api ,T data, int code, String msg){
		api.setCode(code);
		api.setMsg(msg);
		api.setData(data);
		String salt =String.valueOf(Instant.now().toEpochMilli());
		api.setSalt(salt);
		if(data instanceof com.baomidou.mybatisplus.core.metadata.IPage){
			log.info("返回API信息，code: [{}], msg: [{}], salt: [{}], IPage: [{}]",code,msg,salt,((IPage<?>) data).getRecords());
		}else {
			log.info("返回API信息，code: [{}], msg: [{}], salt: [{}], data: [{}]",code,msg,salt,data);
		}

		return api;
	}

}
